package is.web;

import is.interfaces.Bean;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author aspr0
 */
public class SelectOptions<Datatype extends Bean>
{
    public String generate(List<Datatype> beans, Integer selectedId, Boolean nullAllowed, String selectName, Integer... nameIndexes)
    {
        Iterator<Datatype> i = beans.iterator();
        String options = (nullAllowed) ? "<option value=\"\">" + Locale.NULL + "</option>" : "";

        String optionCanvas = "<option value=\"%s\" %s>%s</option>";

        while (i.hasNext())
        {
            Bean bean = i.next();

            String selected = (bean.getId() == selectedId) ? "selected" : "";

            String delimiter = " ";
            String name = "";

            for (int nameIndex : nameIndexes)
            {
                name += (nameIndex < nameIndexes.length - 1)
                        ? bean.getValues()[nameIndex] + delimiter
                        : bean.getValues()[nameIndex];
            }

            options += String.format(optionCanvas, bean.getId(), selected, name);
        }

        String selectCanvas = "<select name=\"%s\" class=\"wide\">%s</select>";
        String select = String.format(selectCanvas, selectName, options);

        return select;
    }
}
